//
//  XVCScanQRCode.m
//  ppkc2016
//
//  Created by 拼凑的断音 on 16/4/15.
//  Copyright © 2016年 拼凑的断音. All rights reserved.
//

#import "XVCScanQRCode.h"
#import "XXTool.h"
#import <AVFoundation/AVFoundation.h>

@interface XVCScanQRCode ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>

@property (nonatomic,strong) UIView *leftMaskView;

@property (nonatomic,strong) UIView *rightMaskView;

@property (nonatomic,strong) UIView *topMaskView;

@property (nonatomic,strong) UIView *bottomMaskView;

@property (nonatomic,strong) VerticalSettingLabel *tipShow;


@property (nonatomic,strong)AVCaptureSession *session;

@property (nonatomic,strong)AVCaptureVideoPreviewLayer *videoPreviewLayer;

@property (strong,nonatomic)AVCaptureDevice * device;

@property (strong,nonatomic)AVCaptureDeviceInput * input;

@property (strong,nonatomic)AVCaptureMetadataOutput * output;

@end

@implementation XVCScanQRCode
{
    BOOL isScaning;
    NSString *reply;
}
- (void)setupCamera
{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    _output.rectOfInterest = CGRectMake([XXTool getHeightWithScreenHeight:150]/self.view.frame.size.height
                                        , [XXTool getWidthWithScreenWidth:120]/self.view.frame.size.width
                                        , [XXTool getWidthWithScreenWidth:510]/self.view.frame.size.height
                                        , [XXTool getWidthWithScreenWidth:510]/self.view.frame.size.width);
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode] ;
    _videoPreviewLayer =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _videoPreviewLayer.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    
    [self.view.layer insertSublayer:self.videoPreviewLayer atIndex:0];
    [_session startRunning];
    
}

-(VerticalSettingLabel*)tipShow
{
    if (_tipShow==nil)
    {
        _tipShow = [[VerticalSettingLabel alloc] init];
        _tipShow.verticalAlignment = VerticalAlignmentTop;
        _tipShow.text = NSLocalizedString(@"将二维码放入框内,即可自动扫描", nil);
        _tipShow.numberOfLines = 0;
        _tipShow.textAlignment = NSTextAlignmentCenter;
        _tipShow.font = [XXTool systemFontOfSize:14];
        _tipShow.textColor = [UIColor whiteColor];
        [self.view addSubview:_tipShow];
    }
    return _tipShow;
}

-(UIView*)leftMaskView
{
    if (_leftMaskView==nil)
    {
        _leftMaskView = [[UIView alloc] init];
        _leftMaskView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
        [self.view addSubview:_leftMaskView];
    }
    return _leftMaskView;
}

-(UIView*)rightMaskView
{
    if (_rightMaskView==nil)
    {
        _rightMaskView = [[UIView alloc] init];
        _rightMaskView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
        [self.view addSubview:_rightMaskView];
    }
    return _rightMaskView;
}

-(UIView*)topMaskView
{
    if (_topMaskView==nil)
    {
        _topMaskView = [[UIView alloc] init];
        _topMaskView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
        [self.view addSubview:_topMaskView];
    }
    return _topMaskView;
}

-(UIView*)bottomMaskView
{
    if (_bottomMaskView==nil)
    {
        _bottomMaskView = [[UIView alloc] init];
        _bottomMaskView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:0.4];
        [self.view addSubview:_bottomMaskView];
    }
    return _bottomMaskView;
}

-(void)initParameter
{
    isScaning = NO;
}

-(void)initUI
{
    [self.navigationItem setTitle:NSLocalizedString(@"扫描二维码", nil)];
    [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"更多"] style:UIBarButtonItemStylePlain target:self action:@selector(clickleft)]];
    
    [self setupCamera];
    [self leftMaskView];
    [self rightMaskView];
    [self topMaskView];
    [self bottomMaskView];
    [self tipShow];
}

-(void)refreshLayout:(CGRect)frame
{
    _leftMaskView.frame = CGRectMake(0
                                     , 0
                                     , [XXTool getWidthWithScreenWidth:120]
                                     , frame.size.height);
    _rightMaskView.frame = CGRectMake(frame.size.width-[XXTool getWidthWithScreenWidth:120]
                                      , 0
                                      , [XXTool getWidthWithScreenWidth:120]
                                      , frame.size.height);
    _topMaskView.frame = CGRectMake(_leftMaskView.frame.size.width
                                    , 0
                                    , frame.size.width-_leftMaskView.frame.size.width*2
                                    , [XXTool getHeightWithScreenHeight:150]);
    _bottomMaskView.frame = CGRectMake(_topMaskView.frame.origin.x
                                       , _topMaskView.frame.size.height+_topMaskView.frame.size.width
                                       , _topMaskView.frame.size.width
                                       , frame.size.height-(_topMaskView.frame.size.height+_topMaskView.frame.size.width));
    
    _tipShow.frame = CGRectMake(_bottomMaskView.frame.origin.x
                                , _bottomMaskView.frame.origin.y+15
                                , _bottomMaskView.frame.size.width
                                , _bottomMaskView.frame.size.height-15);
}

-(void)clickleft
{
    //[self.navigationController.sideViewController showLeftView];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark outputDelegate
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    if (isScaning)
    {
        return;
    }
    NSString *qRCode = nil;
    for (AVMetadataObject *metadata in metadataObjects) {
        if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode]) {
            qRCode = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
            UIAlertView *alt = [[UIAlertView alloc] initWithTitle:@""
                                                          message:[NSString stringWithFormat:@"%@%@",NSLocalizedString(@"扫描结果为:", nil),qRCode]
                                                         delegate:self
                                                cancelButtonTitle:NSLocalizedString(@"取消", nil)
                                                otherButtonTitles:NSLocalizedString(@"复制", nil), nil];
            [alt show];
            reply = qRCode;
            isScaning = YES;
        }
    }
}

#pragma mark alertviewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    isScaning = NO;
    if (buttonIndex==1)
    {
        [UIPasteboard generalPasteboard].string = reply;
        [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"已成功复制到剪切板", nil)];
    }
}

@end
